package com.learn.egcar1.controller;

import com.learn.egcar1.base.response.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Api(tags = "文件上传模块")
@Slf4j
@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    /**
     * 文件上传功能
     *
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //获取原始的文件名
        String filename = file.getOriginalFilename();
        log.debug("原始文件名:{}", filename);
        //获取原始文件名的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        log.debug("文件后缀:{}", suffix);
        //生成全球唯一的文件名
        filename = UUID.randomUUID() + suffix;
        log.debug("新文件名:{}", filename);

        //处理路径
        String dirPath = "D:/files/";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");//自定义日期时间格式
        String dataPath = sdf.format(new Date());//利用日期格式获取
        log.debug("日期路径:{}", dirPath);
        log.debug("文件路径:{}", dirPath + dataPath + filename);

        //创建路径
        File dirFile = new File(dirPath + dataPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        //保存文件
        String filePath = dirPath + dataPath + filename;
        file.transferTo(new File(filePath));

        return JsonResult.ok(filePath);
    }
}
